/**
 * @Author: Jackey 327156719@qq.com
 * @Date: 2024-11-13 16:12:17
 * @LastEditors: Jackey 327156719@qq.com
 * @LastEditTime: 2024-11-13 17:01:30
 * @FilePath: src/main/java/org/springblade/common/config/RestTemplateConfig.java
 * @Description: 这是默认设置,可以在设置》工具》File Description中进行配置
 */
package org.springblade.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Configuration
public class RestTemplateConfig {
	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();

		// 配置连接超时和读取超时
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(30000);
		factory.setReadTimeout(30000);
		restTemplate.setRequestFactory(factory);

		// 添加错误处理器
		restTemplate.setErrorHandler(new ResponseErrorHandler() {
			@Override
			public boolean hasError(ClientHttpResponse response) throws IOException {
				return response.getStatusCode().is4xxClientError()
					|| response.getStatusCode().is5xxServerError();
			}

			@Override
			public void handleError(ClientHttpResponse response) throws IOException {
				throw new HttpClientErrorException(response.getStatusCode());
			}
		});

		return restTemplate;
	}
}
